package com.controller;

import com.entity.User;
import com.util.DataSourceUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;

@WebServlet("/getuser")
public class GetUserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User user = new User();
        String sql = "select * from user where id=?";
        try(Connection connection = DataSourceUtils.getConnection();
            PreparedStatement  ps = connection.prepareStatement(sql)) {
            ps.setString(1, req.getParameter("id"));
            try(ResultSet set = ps.executeQuery()) {
                while (set.next()) {
                    user.setId(set.getString("id"));
                    user.setName(set.getString("name"));
                    user.setInsertTime(set.getObject("insertTime", LocalDateTime.class));
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        req.setAttribute("user", user);
        req.getRequestDispatcher("/WEB-INF/jsp/query.jsp").forward(req, resp);
    }
}
